package com.tz.oa.sysmanage.controller;


import com.tz.oa.sysmanage.entity.Userimg;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("user")
public class UploadController {
    @RequestMapping("/gotoupload")
    public String gotoupload(@ModelAttribute Userimg user, Model model, HttpServletRequest request){
        String rootpath = request.getSession().getServletContext().getRealPath("/upload");
        String fileName=user.getUploadFile().getOriginalFilename();



        File filenTemp=new File(rootpath);
        if (!filenTemp.exists()) {
            filenTemp.mkdir();
        }

        File file=new File(rootpath+"//"+fileName);

        try {
            user.getUploadFile().transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        model.addAttribute("user", user);


        return "uploadsuccess";
    }

    @RequestMapping(value="/download")
    public ResponseEntity<byte[]> download(HttpServletRequest request,
                                           @RequestParam("filename") String filename,
                                           Model model)throws Exception {
        //下载文件路径
        String path = request.getSession().getServletContext().getRealPath("/upload");
        File file = new File(path + File.separator + filename);
        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
        //通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName);
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }
}
